package models

import "github.com/jinzhu/gorm"

type RoomRecord struct {
	Model

	Room string `json:"room"`
}

func ExistRoom(room string) (bool, error) {
	var r RoomRecord
	err := db.Select("id").Where("room = ? AND deleted_on = ?", room, 0).First(&r).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return false, err
	}
	return r.ID > 0, err
}

func ExistRoomById(id int) (bool, error) {
	var room RoomRecord
	err := db.Select("id").Where("id = ? AND deleted_on = ?", id, 0).First(&room).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return false, err
	}
	return room.ID > 0, err
}

func AddRoom(name string) error {
	room := RoomRecord{
		Room: name,
	}
	err := db.Create(&room).Error
	return err
}

// not exclude the deleted
func GetRoomTotal() (int, error) {
	var count int
	err := db.Model(&RoomRecord{}).Count(&count).Error
	if err != nil {
		count = 0
	}
	return count, err
}
func GetRooms(pageNum, pageSize int) ([]*RoomRecord, error) {
	var rooms []*RoomRecord
	err := db.Offset(pageNum).Limit(pageSize).Find(&rooms).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	return rooms, nil
}

func DeleteRoom(id int) error {
	err := db.Where("id = ?", id).Delete(&RoomRecord{}).Error
	return err
}

func CleanAllRoom() error {
	err := db.Unscoped().Where("deleted_on != ?", 0).Delete(&RoomRecord{}).Error
	return err
}
